#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# File Name: m3u8dl.py
# Author: bobo
# Created Time: 20231126

import os
import sys
import time

CMD = "/usr/lib/jellyfin-ffmpeg/ffmpeg"
PARAM = "-c:v hevc_qsv -bsf:a aac_adtstoasc"
# PARAM = "-c:v hevc_qsv -bsf:a aac_adtstoasc -b:v 5M"

def handle_m3u8(m3u8_list):
    for m3u8 in m3u8_list:
        begin = time.time()  # 记录开始时间

        url, fn = m3u8
        print(f"下载：{url} 到 {fn}")
        out_dir = os.path.dirname(fn)
        if out_dir and not os.path.exists(out_dir):
            os.makedirs(out_dir)
        os.system(f'sudo {CMD} -i {url} {PARAM} {fn}')
        #print(f'sudo {CMD} -i {url} {PARAM} {fn}')

        times = time.time() - begin  # 记录完成时间
        print('总消耗时间:'+str(times)+'')

def main():
    m3u8_list = []

    num = len(sys.argv)
    if num < 2 or  num > 3:
        print('参数说明:脚本后面添加 m3u8地址参数，如：m3u8-ffmpeg http://xxx.xxx.com/xxx.m3u8 out.mp4')
        print('或者：m3u8-ffmpeg m3u8列表文件')
        print('文件格式：http://xxx/xxx.m3u8 > outfile.mp4')
        print('\n')
        return
    
    # 文件
    if num == 2:
        lstfile = sys.argv[1]
        if not os.path.exists(lstfile):
            print(f'文件不存在:{lstfile}')
            return
        with open(lstfile, 'r') as fr:
            non_empty_lines = [line.strip() for line in fr.readlines() if line.strip() != ""]
            for line in non_empty_lines:
                url, fn = line.strip().split('>')
                url, fn = url.strip(), fn.strip()
                m3u8_list.append((url, fn))
    # url链接
    elif num == 3:
        url = (sys.argv[1])
        fn = (sys.argv[2])
        m3u8_list.append((url, fn))

    handle_m3u8(m3u8_list)


if __name__ == "__main__":
    main()
